<template>
  <div class="row">
    <!-- 菜单 -->
    <div class="col-md-8">
      <table class="table">
        <thead class="thead-default">
          <tr>
            <th>尺寸</th>
            <th>价格</th>
            <th>加入</th>
          </tr>
        </thead>
        <tbody v-for="item in getMenuItems" :key="item.id">
          <tr>
            <td>
              <strong>{{item.name}}</strong>
            </td>
          </tr>
          <tr v-for="option in JSON.parse(item.options)" :key="option.price">
            <td>{{option.size}}</td>
            <td>{{option.price}}</td>
            <td>
              <button @click="addToBasket(item,option)" class="btn btn-sm btn-outline-success">+</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 购物车 -->
    <div class="col-md-4">
      <table class="table">
        <thead class="thead-default">
          <tr>
            <th>数量</th>
            <th>品种</th>
            <th>价格</th>
          </tr>
        </thead>
        <tbody v-for="item in baskets" :key="item.price">
          <tr>
            <td>
              <button class="btn btn-sm" @click="jianshao(item)">-</button>
              <span>{{item.quantity}}</span>
              <button class="btn btn-sm" @click="zengjia(item)">+</button>
            </td>
            <td>{{item.name}}{{item.size}}</td>
            <td>{{item.quantity*item.price}}</td>
          </tr>
        </tbody>
      </table>

      <p>总价：{{total+ "人民币"}}</p>
      <button class="btn btn-success btn-block">提交</button>
    </div>
    <div></div>
  </div>
</template>



<script>
import axios from "axios";
export default {
  data() {
    return {
      list: [],
      getMenuItems: [],
      baskets:[],
      basketsText: ""
    };
  },

  computed:{

      total(){

        let totalcost=0

        for(let index in this.baskets){
          let individualItem=this.baskets[index]
          totalcost=individualItem.quantity*individualItem.price+totalcost
        }
        return totalcost
      }
  },

  methods:{

    addToBasket(item,option){

      let basket={
        name:item.name,
        size:option.size,
        price:option.price,
        quantity:1
      }

        //将basket对象添加到baskets数组中


      if(this.baskets.length>0){

          let result= this.baskets.filter(basket =>{
              return (basket.name===item.name && basket.price===option.price)
            })

            // console.log(result)

            if(result!=null && result.length>0){
              result[0].quantity++
            }else{
              this.baskets.push(basket)
            }

        }else{
          this.baskets.push(basket)
        }
      },


      zengjia(item){
        item.quantity++
      },

      jianshao(item){
        item.quantity--
      }



  },

  created() {
    axios.get("/menu").then(res => {
      this.getMenuItems = res.data.data;
    });
  }
};
</script>